package com.mars.module.tool.controller;

import com.mars.common.result.R;
import com.mars.common.request.tool.ApiRequest;
import com.mars.common.request.tool.ApiExportRequest;
import com.mars.common.request.tool.ApiQueryRequest;
import com.mars.common.util.SwaggerUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.text.WordUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 接口文档控制器
 *
 * @author 源码字节-程序员Mars
 */
@RestController
@RequestMapping("/tool/api")
@Api(tags = "工具管理-接口文档")
public class SysApiController {

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private Environment env;

    @PostMapping("/list")
    @ApiOperation(value = "获取列表")
    public R<List<ApiRequest>> list(@RequestBody ApiQueryRequest queryDto) {
        if (!StringUtils.hasText(queryDto.getSwaggerUrl())) {
            queryDto.setSwaggerUrl("http://localhost:" + serverPort);
        }
        queryDto.setSwaggerUrl(queryDto.getSwaggerUrl().replace("/swagger-ui.html", "").replace("/doc.html", ""));
        List<ApiRequest> list = SwaggerUtils.getSwaggerData(queryDto.getSwaggerUrl());
        if (StringUtils.hasText(queryDto.getUrl())) {
            list = list.stream().filter(s -> s.getUrl().contains(queryDto.getUrl())).collect(Collectors.toList());
        }
        if (StringUtils.hasText(queryDto.getTitle())) {
            list = list.stream().filter(s -> (s.getTags() + s.getTitle()).contains(queryDto.getTitle())).collect(Collectors.toList());
        }
        list.sort(Comparator.comparing(ApiRequest::getTags));
        return R.success(list);
    }

    /**
     * 获取接口文档地址
     *
     * @return R
     */
    @GetMapping("/getApiUrl")
    @ApiOperation(value = "获取接口文档地址")
    public R<String> getApiUrl() throws UnknownHostException {
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path") != null ? env.getProperty("server.servlet.context-path") : "";
        String url = "http://" + ip + ":" + port + path + "/doc.html";
        return R.success(url);
    }
}
